﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using nRoute.Behaviors.Triggers;

namespace Orktane.Behaviors
{
    public class SetKeyEventHandledBehavior 
        : Behavior<FrameworkElement>
    {
        public static readonly DependencyProperty SetIsHandledProperty =
            DependencyProperty.Register("SetIsHandled", typeof(bool), typeof(SetKeyEventHandledBehavior),
            new PropertyMetadata(false));

#region Properties

        public KeyEventType KeyEvent { get; set; }

        public bool SetIsHandled
        {
            get { return Convert.ToBoolean(GetValue(SetIsHandledProperty)); }
            set { SetValue(SetIsHandledProperty, value);}
        }

#endregion

#region Overrides

        protected override void OnAttached()
        {
            base.OnAttached();
            if (KeyEvent == KeyEventType.KeyDown)
                this.AssociatedObject.KeyDown += new KeyEventHandler(AssociatedObject_KeyEvent);
            else
                this.AssociatedObject.KeyUp += new KeyEventHandler(AssociatedObject_KeyEvent);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            if (KeyEvent == KeyEventType.KeyDown)
                this.AssociatedObject.KeyDown -= new KeyEventHandler(AssociatedObject_KeyEvent);
            else
                this.AssociatedObject.KeyUp -= new KeyEventHandler(AssociatedObject_KeyEvent);
        }

#endregion

#region Handler

        void AssociatedObject_KeyEvent(object sender, KeyEventArgs e)
        {
            e.Handled = SetIsHandled;
        }

#endregion

    }
}
